<!DOCTYPE html>


<html lang="zh_CN">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>Gateway新一代网关 |  MyBlog</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="MyBlog" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="SpringCloud-Gateway新一代网关"
  class="article article-type-SpringCloud"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Gateway新一代网关
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/03/12/Gateway%E6%96%B0%E4%B8%80%E4%BB%A3%E7%BD%91%E5%85%B3/" class="article-date">
  <time datetime="2022-03-12T14:28:20.000Z" itemprop="datePublished">2022-03-12</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/SpringCloud/">SpringCloud</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.8k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">16 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>[TOC]</p>
<h1 id="十二、Gateway新一代网关"><a href="#十二、Gateway新一代网关" class="headerlink" title="十二、Gateway新一代网关"></a>十二、Gateway新一代网关</h1><h2 id="12-1-概述简介"><a href="#12-1-概述简介" class="headerlink" title="12.1.概述简介"></a>12.1.概述简介</h2><h3 id="12-1-1-官网"><a href="#12-1-1-官网" class="headerlink" title="12.1.1.官网"></a>12.1.1.官网</h3><p>zuul：<a target="_blank" rel="noopener" href="https://github.com/Netflix/zuulwiki">https://github.com/Netflix/zuulwiki</a></p>
<p>gateway：<a target="_blank" rel="noopener" href="https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/">https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/</a></p>
<h3 id="12-1-2-Gateway是什么"><a href="#12-1-2-Gateway是什么" class="headerlink" title="12.1.2.Gateway是什么"></a>12.1.2.Gateway是什么</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203052155132.png" alt="image-20220305215532607"></p>
<p>SpringCloud Gateway 是 Spring Cloud 的一个全新项目，<strong>基于 Spring 5.0+Spring Boot 2.0 和 Project Reactor 等技术开发的网关</strong>，它旨在为微服务架构<strong>提供一种简单有效的统一的 API 路由管理方式</strong>。</p>
<p>SpringCloud Gateway 作为 Spring Cloud 生态系统中的网关，<strong>目标是替代 Zuul</strong>，在Spring Cloud 2.0以上版本中，没有对新版本的Zuul 2.0以上最新高性能版本进行集成，仍然还是使用的Zuul 1.x非Reactor模式的老版本。而为了提升网关的性能，<strong>SpringCloud Gateway是基于WebFlux框架实现的</strong>，而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。</p>
<p>SpringCloud Gateway 使用的Webflux中的reactor-netty响应式编程组件，底层使用了Netty通讯框架</p>
<h3 id="12-1-3-Gateway的用途"><a href="#12-1-3-Gateway的用途" class="headerlink" title="12.1.3.Gateway的用途"></a>12.1.3.Gateway的用途</h3><p>反向代理、鉴权、流量控制、熔断、日志监控。。。</p>
<h3 id="12-1-4-微服务架构中网关所处位置"><a href="#12-1-4-微服务架构中网关所处位置" class="headerlink" title="12.1.4.微服务架构中网关所处位置"></a>12.1.4.微服务架构中网关所处位置</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203052159466.png" alt="网关所处位置"></p>
<h3 id="12-1-5-面试中可能会遇到的问题"><a href="#12-1-5-面试中可能会遇到的问题" class="headerlink" title="12.1.5.面试中可能会遇到的问题"></a>12.1.5.面试中可能会遇到的问题</h3><blockquote>
<p>有了Zuul为什么还出来gateway</p>
</blockquote>
<h4 id="1-neiflix不太靠谱，zuul2-0一直跳票，迟迟没有发布"><a href="#1-neiflix不太靠谱，zuul2-0一直跳票，迟迟没有发布" class="headerlink" title="1.neiflix不太靠谱，zuul2.0一直跳票，迟迟没有发布"></a>1.neiflix不太靠谱，zuul2.0一直跳票，迟迟没有发布</h4><p>一方面因为Zuul1.0已经进入了维护阶段，而且Gateway是SpringCloud团队研发的，是亲儿子产品，值得信赖。<br>而且很多功能Zuul都没有用起来也非常的简单便捷。</p>
<p>Gateway是基于异步非阻塞模型上进行开发的，性能方面不需要担心。虽然Netflix早就发布了最新的 Zuul 2.x，<br>但 Spring Cloud 貌似没有整合计划。而且Netflix相关组件都宣布进入维护期；不知前景如何？</p>
<p>多方面综合考虑Gateway是很理想的网关选择。</p>
<h4 id="2-Gateway具有如下特性"><a href="#2-Gateway具有如下特性" class="headerlink" title="2.Gateway具有如下特性"></a>2.Gateway具有如下特性</h4><ul>
<li><strong>基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建；</strong></li>
<li>动态路由：能够匹配任何请求属性；</li>
<li>可以对路由指定 Predicate（断言）和 Filter（过滤器）；</li>
<li>集成Hystrix的断路器功能；</li>
<li>集成 Spring Cloud <strong>服务发现功能</strong>；</li>
<li>易于编写的 Predicate（断言）和 Filter（过滤器）；</li>
<li>请求限流功能；</li>
<li>支持路径重写。</li>
</ul>
<h4 id="3-SpringCloud-Gateway和Zuul的区别"><a href="#3-SpringCloud-Gateway和Zuul的区别" class="headerlink" title="3.SpringCloud Gateway和Zuul的区别"></a><font color='red'>3.SpringCloud Gateway和Zuul的区别</font></h4><p>在SpringCloud Finchley 正式版之前，Spring Cloud 推荐的网关是 Netflix 提供的Zuul：</p>
<p>1、Zuul 1.x，是一个基于阻塞 I/ O 的 API Gateway</p>
<p>2、Zuul 1.x <strong>基于Servlet 2. 5使用阻塞架构</strong>它不支持任何长连接(如 WebSocket) Zuul 的设计模式和Nginx较像，每次 I/ O 操作都是从工作线程中选择一个执行，请求线程被阻塞到工作线程完成，但是差别是Nginx 用C++ 实现，Zuul 用 Java 实现，而 JVM 本身会有第一次加载较慢的情况，使得Zuul 的性能相对较差。</p>
<p>3、Zuul 2.x理念更先进，想基于Netty非阻塞和支持长连接，但SpringCloud目前还没有整合。 Zuul 2.x的性能较 Zuul 1.x 有较大提升。在性能方面，根据官方提供的基准测试， Spring Cloud Gateway 的 RPS（每秒请求数）是Zuul 的 1. 6 倍。</p>
<p>4、Spring Cloud Gateway 建立 在 Spring Framework 5、 Project Reactor 和 Spring Boot 2 之上， 使用非阻塞 API。</p>
<p>5、Spring Cloud Gateway 还支持 WebSocket， 并且与Spring紧密集成拥有更好的开发体验</p>
<h4 id="4-Zuul模型"><a href="#4-Zuul模型" class="headerlink" title="4.Zuul模型"></a>4.Zuul模型</h4><p>servlet由servlet container进行生命周期管理。</p>
<ol>
<li>container启动时构造servlet对象并调用servlet **init()**进行初始化；</li>
<li>container运行时接受请求，并为每个请求分配一个线程（一般从线程池中获取空闲线程）然后调用**service()**。</li>
<li>container关闭时调用servlet **destory()**销毁servlet；</li>
</ol>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203052208267.png" alt="image-20220305220800309"></p>
<p><font color='blue'>上述模式的缺点：</font></p>
<p>servlet是一个简单的网络IO模型，当请求进入servlet container时，servlet container就会为其绑定一个线程，在并发不高的场景下这种模型是适用的。但是一旦高并发(比如抽风用jemeter压)，线程数量就会上涨，而线程资源代价是昂贵的（上下文切换，内存消耗大）严重影响请求的处理时间。在一些简单业务场景下，不希望为每个request分配一个线程，只需要1个或几个线程就能应对极大并发的请求，这种业务场景下servlet模型没有优势</p>
<p>所以Zuul 1.X是<strong>基于servlet之上的一个阻塞式处理模型</strong>，即spring实现了处理所有request请求的一个servlet（DispatcherServlet）并由该servlet阻塞式处理处理。所以Springcloud Zuul<strong>无法摆脱servlet模型的弊端</strong></p>
<h4 id="5-Gateway模型"><a href="#5-Gateway模型" class="headerlink" title="5.Gateway模型"></a>5.Gateway模型</h4><p>了解webflux</p>
<p><strong>官网</strong>：<a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/5.2.19.RELEASE/spring-framework-reference/web-reactive.html#webflux">https://docs.spring.io/spring-framework/docs/5.2.19.RELEASE/spring-framework-reference/web-reactive.html#webflux</a></p>
<p><strong>说明</strong></p>
<p>传统的Web框架，比如说：struts2，springmvc等都是基于Servlet API与Servlet容器基础之上运行的。<br>但是<br>在Servlet3.1之后有了异步非阻塞的支持。而WebFlux是一个典型非阻塞异步的框架，它的核心是基于Reactor的相关API实现的。相对于传统的web框架来说，它可以运行在诸如Netty，Undertow及支持Servlet3.1的容器上。<strong>非阻塞式+函数式编程</strong>（Spring5必须让你使用java8）</p>
<p>Spring WebFlux 是 Spring 5.0 引入的新的响应式框架，区别于 Spring MVC，它不需要依赖Servlet API，它是完全异步非阻塞的，并且基于 Reactor 来实现响应式流规范。</p>
<h2 id="12-2-三大核心概念"><a href="#12-2-三大核心概念" class="headerlink" title="12.2.三大核心概念"></a>12.2.三大核心概念</h2><h3 id="12-2-1-Route（路由）"><a href="#12-2-1-Route（路由）" class="headerlink" title="12.2.1.Route（路由）"></a>12.2.1.Route（路由）</h3><p>路由是构建网关的基本模块，它由ID，目标URI，一系列的<strong>断言和过滤器组成</strong>，如果<strong>断言为true则匹配该路由</strong></p>
<h3 id="12-2-2-Predicate（断言）"><a href="#12-2-2-Predicate（断言）" class="headerlink" title="12.2.2.Predicate（断言）"></a>12.2.2.Predicate（断言）</h3><p>参考的是java8的java.util.function.Predicate，开发人员可以匹配HTTP请求中的所有内容（例如请求头或请求参数），<font color='red'>如果请求与断言想匹配则进行路由</font></p>
<h3 id="12-2-3-Filter（过滤）"><a href="#12-2-3-Filter（过滤）" class="headerlink" title="12.2.3.Filter（过滤）"></a>12.2.3.Filter（过滤）</h3><p>指的是Spring框架中GatewayFilter的实例，使用过滤器，可以在请求被路由前或者之后对请求进行修改</p>
<h3 id="12-2-4-总体"><a href="#12-2-4-总体" class="headerlink" title="12.2.4.总体"></a>12.2.4.总体</h3><p>web请求，通过一些匹配条件，定位到真正的服务节点。并在这个转发过程的前后，进行一些精细化控制。</p>
<p><strong>predicate就是我们的匹配条件</strong>；</p>
<p>而filter，就可以理解为一个无所不能的拦截器。有了这两个元素，再加上目标uri，就可以实现一个具体的路由了</p>
<h2 id="12-3-Gateway工作流程"><a href="#12-3-Gateway工作流程" class="headerlink" title="12.3.Gateway工作流程"></a>12.3.Gateway工作流程</h2><h3 id="12-3-1-官网总结"><a href="#12-3-1-官网总结" class="headerlink" title="12.3.1.官网总结"></a>12.3.1.官网总结</h3><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203052219971.png" alt="image-20220305221905444"></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203052219810.png" alt="image-20220305221922329"></p>
<p>客户端向 Spring Cloud Gateway 发出请求。然后在 Gateway Handler Mapping 中找到与请求相匹配的路由，将其发送到 Gateway Web Handler。</p>
<p>Handler 再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑，然后返回。过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前（“pre”）或之后（“post”）执行业务逻辑。</p>
<p>Filter在“pre”类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等，在“post”类型的过滤器中可以做响应内容、响应头的修改，日志的输出，流量监控等有着非常重要的作用</p>
<h3 id="12-3-2-核心逻辑"><a href="#12-3-2-核心逻辑" class="headerlink" title="12.3.2.核心逻辑"></a>12.3.2.核心逻辑</h3><p><font color='red'><strong>路由转发 + 执行过滤器链</strong></font></p>
<h2 id="12-4-入门配置"><a href="#12-4-入门配置" class="headerlink" title="12.4.入门配置"></a>12.4.入门配置</h2><h3 id="12-4-1-新建模块cloud-gateway-gateway9527"><a href="#12-4-1-新建模块cloud-gateway-gateway9527" class="headerlink" title="12.4.1.新建模块cloud-gateway-gateway9527"></a>12.4.1.新建模块cloud-gateway-gateway9527</h3><h3 id="12-4-2-修改pom"><a href="#12-4-2-修改pom" class="headerlink" title="12.4.2.修改pom"></a>12.4.2.修改pom</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">     <span class="comment">&lt;!--gateway--&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-gateway<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="comment">&lt;!--eureka-client--&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-eureka-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="comment">&lt;!-- 引入自己定义的api通用包，可以使用Payment支付Entity --&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.atyuan<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cloud-api-commons<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="comment">&lt;!--一般基础配置类--&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-devtools<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="12-4-3-写yml"><a href="#12-4-3-写yml" class="headerlink" title="12.4.3.写yml"></a>12.4.3.写yml</h3><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">9527</span></span><br><span class="line"></span><br><span class="line"><span class="string">spring:a</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">cloud-gateway</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">      <span class="attr">routes:</span></span><br><span class="line">        <span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_routh</span> <span class="comment">#payment_route    #路由的ID，没有固定规则但要求唯一，建议配合服务名</span></span><br><span class="line">          <span class="attr">uri:</span> <span class="string">http://localhost:8001</span>          <span class="comment">#匹配后提供服务的路由地址</span></span><br><span class="line">          <span class="attr">predicates:</span></span><br><span class="line">            <span class="bullet">-</span> <span class="string">Path=/payment/get/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line"></span><br><span class="line">        <span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_routh2</span> <span class="comment">#payment_route    #路由的ID，没有固定规则但要求唯一，建议配合服务名</span></span><br><span class="line">          <span class="attr">uri:</span> <span class="string">http://localhost:8001</span>          <span class="comment">#匹配后提供服务的路由地址</span></span><br><span class="line">          <span class="attr">predicates:</span></span><br><span class="line">            <span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="attr">eureka:</span></span><br><span class="line">  <span class="attr">instance:</span></span><br><span class="line">    <span class="attr">hostname:</span> <span class="string">cloud-gateway-service</span></span><br><span class="line">  <span class="attr">client:</span> <span class="comment">#服务提供者provider注册进eureka服务列表内</span></span><br><span class="line">    <span class="attr">service-url:</span></span><br><span class="line">      <span class="attr">register-with-eureka:</span> <span class="literal">true</span></span><br><span class="line">      <span class="attr">fetch-registry:</span> <span class="literal">true</span></span><br><span class="line">      <span class="attr">defaultZone:</span> <span class="string">http://eureka7001.com:7001/eureka</span></span><br></pre></td></tr></table></figure>

<h3 id="12-4-4-创建主启动类"><a href="#12-4-4-创建主启动类" class="headerlink" title="12.4.4.创建主启动类"></a>12.4.4.创建主启动类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="meta">@EnableEurekaClient</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GateWayMain9527</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        SpringApplication.run(GateWayMain9527.class,args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="12-4-5-测试"><a href="#12-4-5-测试" class="headerlink" title="12.4.5.测试"></a>12.4.5.测试</h3><p>先启动7001服务注册中心eureka</p>
<p>再启动8001服务提供者</p>
<p>最后启动路由网关</p>
<p>访问测试：<a target="_blank" rel="noopener" href="http://localhost:9527/payment/get/8">http://localhost:9527/payment/get/8</a></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061107894.png" alt="测试结果"></p>
<h3 id="12-4-6-路由网关的两种配置方式"><a href="#12-4-6-路由网关的两种配置方式" class="headerlink" title="12.4.6.路由网关的两种配置方式"></a>12.4.6.路由网关的两种配置方式</h3><h4 id="1-在配置文件yml中配置"><a href="#1-在配置文件yml中配置" class="headerlink" title="1.在配置文件yml中配置"></a>1.在配置文件yml中配置</h4><p>上述这种方式</p>
<h4 id="2-通过代码注入到IOC容器中"><a href="#2-通过代码注入到IOC容器中" class="headerlink" title="2.通过代码注入到IOC容器中"></a>2.通过代码注入到IOC容器中</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GateWayConfig</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RouteLocator <span class="title">customRouteLocator</span><span class="params">(RouteLocatorBuilder builder)</span></span>&#123;</span><br><span class="line">        RouteLocatorBuilder.Builder routes = builder.routes();</span><br><span class="line">        routes.route(<span class="string">&quot;payment_yuan_route&quot;</span>,r -&gt; r.path(<span class="string">&quot;/&quot;</span>).uri(<span class="string">&quot;https://www.baidu.com/&quot;</span>));</span><br><span class="line">        <span class="keyword">return</span> routes.build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="12-5-通过服务名实现动态路由"><a href="#12-5-通过服务名实现动态路由" class="headerlink" title="12.5.通过服务名实现动态路由"></a>12.5.通过服务名实现动态路由</h2><h3 id="12-5-1-修改9527的yml文件"><a href="#12-5-1-修改9527的yml文件" class="headerlink" title="12.5.1.修改9527的yml文件"></a>12.5.1.修改9527的yml文件</h3><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line">  <span class="attr">port:</span> <span class="number">9527</span></span><br><span class="line"></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">application:</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">cloud-gateway</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">      <span class="attr">discovery:</span></span><br><span class="line">        <span class="attr">locator:</span></span><br><span class="line">          <span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">      <span class="attr">routes:</span></span><br><span class="line">        <span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_routh</span> <span class="comment">#payment_route    #路由的ID，没有固定规则但要求唯一，建议配合服务名</span></span><br><span class="line"><span class="comment">#          uri: http://localhost:8001          #匹配后提供服务的路由地址</span></span><br><span class="line">          <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">          <span class="attr">predicates:</span></span><br><span class="line">            <span class="bullet">-</span> <span class="string">Path=/payment/get/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line"></span><br><span class="line">        <span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_routh2</span> <span class="comment">#payment_route    #路由的ID，没有固定规则但要求唯一，建议配合服务名</span></span><br><span class="line"><span class="comment">#          uri: http://localhost:8001          #匹配后提供服务的路由地址</span></span><br><span class="line">          <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">          <span class="attr">predicates:</span></span><br><span class="line">            <span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="attr">eureka:</span></span><br><span class="line">  <span class="attr">instance:</span></span><br><span class="line">    <span class="attr">hostname:</span> <span class="string">cloud-gateway-service</span></span><br><span class="line">  <span class="attr">client:</span> <span class="comment">#服务提供者provider注册进eureka服务列表内</span></span><br><span class="line">    <span class="attr">service-url:</span></span><br><span class="line">      <span class="attr">register-with-eureka:</span> <span class="literal">true</span></span><br><span class="line">      <span class="attr">fetch-registry:</span> <span class="literal">true</span></span><br><span class="line">      <span class="attr">defaultZone:</span> <span class="string">http://eureka7001.com:7001/eureka</span></span><br></pre></td></tr></table></figure>

<p>需要注意的是uri的协议为lb，表示启用gateway的负载均衡功能</p>
<p>lb://serviceName是springcloud gateway在微服务中自动为我们创建的负载均衡uri</p>
<h3 id="12-5-3-测试"><a href="#12-5-3-测试" class="headerlink" title="12.5.3.测试"></a>12.5.3.测试</h3><p><a target="_blank" rel="noopener" href="http://localhost:9527/payment/lb">http://localhost:9527/payment/lb</a></p>
<p>测试结果</p>
<p>8001和8002端口来回切换</p>
<h2 id="12-6-Predicate的使用"><a href="#12-6-Predicate的使用" class="headerlink" title="12.6.Predicate的使用"></a>12.6.Predicate的使用</h2><p>官网地址：<a target="_blank" rel="noopener" href="https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories">https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories</a></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061305847.png" alt="image-20220306130552571"></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061310698.png" alt="image-20220306131036561"></p>
<p>Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分。</p>
<p>Spring Cloud Gateway包括许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个Route Predicate工厂可以进行组合</p>
<p>Spring Cloud Gateway 创建 Route 对象时， 使用 RoutePredicateFactory 创建 Predicate 对象，Predicate 对象可以赋值给 Route。 <strong>Spring Cloud Gateway 包含许多内置的Route Predicate Factories</strong>。</p>
<p>所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合，并通过逻辑and。</p>
<h3 id="常用的Predicate"><a href="#常用的Predicate" class="headerlink" title="常用的Predicate"></a>常用的Predicate</h3><h4 id="1-After-Route-Predicate"><a href="#1-After-Route-Predicate" class="headerlink" title="1.After Route Predicate"></a>1.After Route Predicate</h4><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061349486.png" alt="image-20220306134929125"></p>
<blockquote>
<p>查询默认时区</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">T2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        ZonedDateTime dateTime = ZonedDateTime.now();  <span class="comment">//默认时区</span></span><br><span class="line">        <span class="comment">// 2022-03-06T13:19:39.444+08:00[Asia/Shanghai]</span></span><br><span class="line">        System.out.println(dateTime);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>YML文件</p>
</blockquote>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">            	<span class="bullet">-</span> <span class="string">After=2022-03-06T13:19:39.444+08:00[Asia/Shanghai]</span></span><br></pre></td></tr></table></figure>

<h4 id="2-Before-Route-Predicate"><a href="#2-Before-Route-Predicate" class="headerlink" title="2.Before Route Predicate"></a>2.Before Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">            	<span class="bullet">-</span> <span class="string">Before=2022-03-06T13:19:39.444+08:00[Asia/Shanghai]</span></span><br></pre></td></tr></table></figure>

<h4 id="3-Between-Route-Predicate"><a href="#3-Between-Route-Predicate" class="headerlink" title="3.Between Route Predicate"></a>3.Between Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">            	<span class="bullet">-</span> <span class="string">Before=2021-02-06T13:19:39.444+08:00[Asia/Shanghai],2022-05-06T13:19:39.444+08:00[Asia/Shanghai]</span></span><br></pre></td></tr></table></figure>

<h4 id="4-Cookie-Route-Predicate"><a href="#4-Cookie-Route-Predicate" class="headerlink" title="4.Cookie Route Predicate"></a>4.Cookie Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Cookie=username,yuan</span></span><br></pre></td></tr></table></figure>

<h4 id="5-Header-Route-Predicate"><a href="#5-Header-Route-Predicate" class="headerlink" title="5.Header Route Predicate"></a>5.Header Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">				<span class="bullet">-</span> <span class="string">Header=X-Request-Id,\d+</span></span><br></pre></td></tr></table></figure>

<h4 id="6-Host-Route-Predicate"><a href="#6-Host-Route-Predicate" class="headerlink" title="6.Host Route Predicate"></a>6.Host Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">				<span class="bullet">-</span> <span class="string">Host=gateway.com</span></span><br></pre></td></tr></table></figure>

<h4 id="7-Method-Route-Predicate"><a href="#7-Method-Route-Predicate" class="headerlink" title="7.Method Route Predicate"></a>7.Method Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">				<span class="bullet">-</span> <span class="string">Method=GET</span></span><br></pre></td></tr></table></figure>

<h4 id="8-Path-Route-Predicate"><a href="#8-Path-Route-Predicate" class="headerlink" title="8.Path Route Predicate"></a>8.Path Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br></pre></td></tr></table></figure>

<h4 id="9-Query-Route-Predicate"><a href="#9-Query-Route-Predicate" class="headerlink" title="9.Query Route Predicate"></a>9.Query Route Predicate</h4><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">cloud:</span></span><br><span class="line">    <span class="attr">gateway:</span></span><br><span class="line">        <span class="attr">discovery:</span></span><br><span class="line">        	<span class="attr">locator:</span></span><br><span class="line">        		<span class="attr">enabled:</span> <span class="literal">true</span> <span class="comment">#开启从注册中心动态创建路由的功能，利用微服务名进行路由</span></span><br><span class="line">       	<span class="attr">routes:</span></span><br><span class="line">       	 	<span class="bullet">-</span> <span class="attr">id:</span> <span class="string">payment_route</span></span><br><span class="line">       	   	  <span class="attr">uri:</span> <span class="string">lb://cloud-payment-service</span></span><br><span class="line">       	   	  <span class="attr">predicates:</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Path=/payment/lb/**</span>         <span class="comment"># 断言，路径相匹配的进行路由</span></span><br><span class="line">       	   	  	<span class="bullet">-</span> <span class="string">Query=username,</span> <span class="string">\d+</span>  <span class="comment"># 要有参数名username并且值还要是整数才能路由</span></span><br></pre></td></tr></table></figure>

<h4 id="10-测试"><a href="#10-测试" class="headerlink" title="10.测试"></a>10.测试</h4><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061404053.png" alt="image-20220306140359663"></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">curl http://localhost:9527/payment/lb --cookie <span class="string">&quot;username=yuan&quot;</span> -H <span class="string">&quot;X-Request-Id&quot;</span></span><br></pre></td></tr></table></figure>

<p>断言的条件需要同时满足，否则是无法访问的</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061341609.png" alt="image-20220306134150478"></p>
<h2 id="12-7-Filter的使用"><a href="#12-7-Filter的使用" class="headerlink" title="12.7.Filter的使用"></a>12.7.Filter的使用</h2><p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061506861.png" alt="GatewayFilter Factories介绍"></p>
<p>路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应，路由过滤器只能指定路由进行使用。</p>
<p>Spring Cloud Gateway 内置了多种路由过滤器，他们都由GatewayFilter的工厂类来产生</p>
<h3 id="12-7-1-Spring-Cloud-Gateway的Filter"><a href="#12-7-1-Spring-Cloud-Gateway的Filter" class="headerlink" title="12.7.1.Spring Cloud Gateway的Filter"></a>12.7.1.Spring Cloud Gateway的Filter</h3><p>GatewayFilter、GlobalFilter（内置的Filter可看官网介绍）</p>
<h3 id="12-7-2-自定义全局GlobalFilter"><a href="#12-7-2-自定义全局GlobalFilter" class="headerlink" title="12.7.2.自定义全局GlobalFilter"></a>12.7.2.自定义全局GlobalFilter</h3><p>实现两个接口GlobalFilter，Ordered</p>
<p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyGateWayFilter</span> <span class="keyword">implements</span> <span class="title">GlobalFilter</span>, <span class="title">Ordered</span> </span>&#123;</span><br><span class="line">    <span class="comment">//过滤规则</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Mono&lt;Void&gt; <span class="title">filter</span><span class="params">(ServerWebExchange exchange, GatewayFilterChain chain)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;time:&quot;</span>+<span class="keyword">new</span> Date()+<span class="string">&quot;\t 执行了自定义的全局过滤器: &quot;</span>+<span class="string">&quot;MyLogGateWayFilter&quot;</span>+<span class="string">&quot;hello&quot;</span>);</span><br><span class="line">        String uname = exchange.getRequest().getQueryParams().getFirst(<span class="string">&quot;uname&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">null</span> == uname)&#123;</span><br><span class="line">            log.info(<span class="string">&quot;***** uname=null,无法登录 *****&quot;</span>);</span><br><span class="line">            exchange.getResponse().setStatusCode(HttpStatus.HTTP_VERSION_NOT_SUPPORTED);</span><br><span class="line">            <span class="keyword">return</span> exchange.getResponse().setComplete();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="12-7-3-测试"><a href="#12-7-3-测试" class="headerlink" title="12.7.3.测试"></a>12.7.3.测试</h3><p>先启动7001，再启动8001和8002，最后启动9527</p>
<p>访问：<a target="_blank" rel="noopener" href="http://localhost:9527/payment/lb?uname=yuan">http://localhost:9527/payment/lb?uname=yuan</a>      <font color="green"><strong>√成功</strong></font></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061522603.png" alt="image-20220306152216593"></p>
<p>访问：<a target="_blank" rel="noopener" href="http://localhost:9527/payment/lb">http://localhost:9527/payment/lb</a>       <font color='red'><strong>×失败</strong></font></p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061522379.png" alt="image-20220306152252175"></p>
<p>接着观察后台所输出的内容</p>
<p><img src="https://gitee.com/RMByuan/note-material/raw/master/studyImg/202203061524483.png" alt="控制台输出"></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2022/03/12/Gateway%E6%96%B0%E4%B8%80%E4%BB%A3%E7%BD%91%E5%85%B3/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/SpringCloud/" rel="tag">SpringCloud</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
    
      <a href="/2022/03/12/OpenFeign%E6%9C%8D%E5%8A%A1%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">OpenFeign服务接口调用</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> Yuan
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="MyBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->
 
<script src="/js/clickLove.js"></script>
 
<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=22707008&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
    

  </div>
</body>

</html>